package com.para.esc.web.common;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;


import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import com.smart.sso.client.util.HttpsRequestUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import org.apache.http.util.EntityUtils;


public class APIUtil {
	public static final String APP_SECRET_KEY = "93b599864ef9d02dd79c1a6cd0255cd8";
	public static final String url = "https://ssotst.smedi.com:8443";
	public static final String client_ID = "c0JZOU3K5d"; //应用注册ID
	public static final String client_secret = "92a7d4a2-a3ca-4cfb-b572-75938362b3ac"; //应用注册秘钥
	public static final String redirect_uri = "http://10.0.0.102:8084/back";
	public static final String nonce_str = UUID.randomUUID().toString();



	public static void main(String[] args) throws Exception {

		/*String token= APIUtil.getAccessTokenParam("ST-9730-szZGGep0UOt9HAAz1ufx");
		System.out.println("token--------------"+token);
		//System.out.println(getResult(url, param));*/
	}
	/**
	 * 心跳检测
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	public static String xTJC() throws NoSuchAlgorithmException, UnsupportedEncodingException{ 
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
    	String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
    	String oauth_timestamp = Date2TimeStamp(date,"yyyy-MM-dd HH:mm:ss"); //时间戳
    	String appkey=APP_SECRET_KEY;
    	Map<String, Object> M = new HashMap<String, Object>();
    	M.put("client_id", client_ID);
		M.put("client_secret", client_secret);
		M.put("nonce_str", nonce_str);
		M.put("oauth_timestamp",oauth_timestamp);
		String sign = getSign(M, appkey+client_secret);


		M.put("sign",sign);
		String url1 = url+"/service/api/v1/oauth2/checkSSOService";
		String result= httpsApi(M, url1,"POST");
		return result;//请求的结果在里面
	}
	/**
	 * sso请求地址重定向
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	public static String SSORequest() throws NoSuchAlgorithmException, UnsupportedEncodingException{
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
    	String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
    	String oauth_timestamp = Date2TimeStamp(date,"yyyy-MM-dd HH:mm:ss"); //时间戳
		String url2 = url+"/profile/oauth2/authorize?client_id="+client_ID+"&response_type=code&redirect_uri="+redirect_uri+"&oauth_timestamp="+oauth_timestamp;
		return url2; 
		
	}
	/**
	 * 获取token
	 * @param code
	 * @return
	 */
	public static String getAccessTokenParam(String code) {
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
    	String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
		System.out.println("-----------df-----------------"+date);
    	String oauth_timestamp = Date2TimeStamp(date,"yyyy-MM-dd HH:mm:ss"); //时间戳
    
    	String appkey=APP_SECRET_KEY;
  
    	Map<String, Object> M = new HashMap<String, Object>();
    	M.put("client_id", client_ID);
		M.put("client_secret", client_secret);
		M.put("nonce_str", nonce_str);
		M.put("oauth_timestamp",oauth_timestamp);
		M.put("grant_type","authorization_code");
		M.put("code", code);
		M.put("redirect_uri",redirect_uri);
		String sign = getSign(M, appkey+client_secret);
		M.put("sign", sign);

		System.out.println("sign---"+sign);
		System.out.println("nonce_str---"+nonce_str);
		String url2 = url+"/profile/oauth2/accessToken";
		String result= httpsApi(M, url2,"POST");
		return result;//请求的结果在里面
		
	}
	/**
	 * 根据access_token获取用户参数(含签名)方法
	 * @return 页面相应的结果
	 */
	public static String getUserParam(String access_token){
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
    	String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
    	String oauth_timestamp = Date2TimeStamp(date,"yyyy-MM-dd HH:mm:ss"); //时间戳
    	String appkey=APP_SECRET_KEY;
    	Map<String, Object> M = new HashMap<String, Object>();
    	M.put("client_id", client_ID);
		M.put("client_secret", client_secret);
		M.put("nonce_str", nonce_str);
		M.put("oauth_timestamp",oauth_timestamp);
		M.put("access_token", access_token);
		String sign = getSign(M, appkey+client_secret);
		M.put("sign", sign);

		String url3 = url+"/profile/oauth2/profile";
		String result= httpsApi(M, url3,"POST");
		return result;//请求的结果在里面
	}
	
	/**
	 * 日期格式转换为自定义的"yyyy-MM-dd HH:mm:ss"
	 * @param dateStr
	 * @param format
	 * @return
	 */
	public static String Date2TimeStamp(String dateStr, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return String.valueOf(sdf.parse(dateStr).getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
	
	//对参数排序并用md5加密
	public static String getSign(Map<String, Object> params,String secret)    
	    {    
	        String sign="";    
	        StringBuilder sb = new StringBuilder();   
	        //排序  
	        Set<String> keyset=params.keySet();    
	        TreeSet<String> sortSet=new TreeSet<String>();    
	        sortSet.addAll(keyset);    
	        Iterator<String> it=sortSet.iterator();   
	        //加密字符串  
	        while(it.hasNext())    
	        {    
	            String key=it.next();    
	            String value=params.get(key).toString();    
	            sb.append(key).append(value);    
	        }    
	        sb.append("appkey").append(secret);  
	        try {    
	           sign=  MD5Util.md5s(sb.toString()).toUpperCase();
	        } catch (Exception e) {    
	        }    
	        return sign;    
	    } 

	public static String  httpsApi(Map<String, Object> context, String url,String methodType) {
		String temp = null;
		HttpResponse<String> jsonResponse = null;	
		try {
			Unirest.setHttpClient(createSSLClient());
			if(methodType.equals("GET")){
				jsonResponse = Unirest.get(url)
		        .header("Connection", "Keep-Alive")
		        .header("Content-Type", "application/x-www-form-urlencoded").asString();	
			}else if(methodType.equals("POST")){
				System.out.println("------------------------------发送请求------------------------------------------");
				jsonResponse = Unirest.post(url)
		        .header("Connection", "Keep-Alive")
		        .header("Content-Type", "application/x-www-form-urlencoded").fields(context).asString();
			}else if(methodType.equals("PUT")){
				jsonResponse = Unirest.put(url)
		        .header("Connection", "Keep-Alive")
		        .header("Content-Type", "application/x-www-form-urlencoded").fields(context).asString();	
			}else if(methodType.equals("DELETE")){
				jsonResponse = Unirest.delete(url)
		        .header("Connection", "Keep-Alive")
		        .header("Content-Type", "application/x-www-form-urlencoded").fields(context).asString();
			}else if(methodType.equals("JSON")){
				jsonResponse = Unirest.post(url)
		        .header("Connection", "Keep-Alive").header("Content-Type", "application/json").body((String)context.get("jsonStrs")).asString();
				
			}		
			temp = jsonResponse.getBody();			
		} catch (Exception e) {
			System.out.println("调用地址"+url+"异常信息"+e.getLocalizedMessage());
			e.printStackTrace();
		}
		return temp;
	}
	
	private static CloseableHttpClient createSSLClient() {
		TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
			
			@Override
			public boolean isTrusted(java.security.cert.X509Certificate[] arg0,
					String arg1) throws java.security.cert.CertificateException {
				// TODO Auto-generated method stub
				return true;
			}
		};
 
		SSLContext sslContext = null;
		try {
			sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
		} catch (Exception e) {
			
		}
		return HttpClients.custom().setSslcontext(sslContext).setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();
	}


	
	 public class TrustAnyHostnameVerifier implements HostnameVerifier {
		  public boolean verify(String hostname, SSLSession session) {
		   // 直接返回true
		   return true;
		  }
		 }
	

}
